<template>
  <div class="field-form-container">
    <div class="tool-bar">
      <el-button
        type="primary"
        size="mini"
        icon="el-icon-plus"
        @click="handleAdd"
      >新增</el-button>
      <el-button
        size="mini"
        icon="el-icon-edit"
        @click="handleEdit"
      >编辑</el-button>
      <el-button
        size="mini"
        icon="el-icon-delete"
        @click="handleDelete()"
      >删除</el-button>
      <el-button
        size="mini"
        icon="el-icon-setting"
        @click="handleUniqueVerifySetting()"
      >数据唯一校验</el-button>
    </div>
    <div class="table-container">
      <el-table
        ref="Table"
        :data="fieldList"
        stripe
        border
        tooltip-effect="dark"
        style="width: 100%"
        height="100%"
        @row-click="handleRowClick"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        >
        </el-table-column>
        <el-table-column
          v-for="col in columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.width"
          :min-width="col.minWidth"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            <span v-if="col.showLabel">{{col.showLabel(row[col.prop])}}</span>
            <span v-else>{{row[col.prop]}}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <FormDialog
      ref="Form"
      :visible.sync="dialog.visible"
      :title="dialog.isEdit?'编辑':'新增'"
      width="85%"
      :defaultItems="dialog.items"
      :columnNum="2"
      :isInit="dialog.isInit"
      :autoCloseAfterSubmit="false"
      @table-select-open="handleTableSelectOpen"
      @table-pager-change="handleTableSelectOpen"
      @table-search="handleTableSelectOpen"
      @submit-form="handleSubmitForm"
    ></FormDialog>
    <UniqueValidDailog
      ref="UniqueValidDailog"
      :visible.sync="uniqueValidDailog.visible"
      :defaultValue="uniqueValidDailog.defaultValue"
      :fieldList="fieldList"
      :tableId="data.id"
      @submit-form="handleUniqueSubmitForm"
    ></UniqueValidDailog>
  </div>
</template>
<script>
import FormDialog from '@/components/FormDialog'
import UniqueValidDailog from './uniqueValidDailog'
import { getFieldFormItems } from '../formItem'
import { DATATYPE, REQUIRED, MAPPERTODB, VALUEMAPTYPE } from '../../enum'
import {
  getFieldListByTable,
  getTables,
  getAllFieldListByTable
} from '@/api/import/template'
export default {
  components: { FormDialog, UniqueValidDailog },
  props: {
    data: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      columns: [
        { prop: 'excelColumnCode', label: 'excel列编码', width: '120' },
        { prop: 'excelColumnName', label: 'excel列名', minWidth: '120' },
        { prop: 'orderNo', label: '排序号', minWidth: '120' },
        {
          prop: 'required',
          label: '必填',
          minWidth: '120',
          showLabel(value) {
            const _value = REQUIRED.find((ele) => ele.value === value)
            return _value ? _value.label : ''
          }
        },
        {
          prop: 'excelColumnDataType',
          label: 'excel列数据类型',
          minWidth: '120',
          showLabel(value) {
            const _value = DATATYPE.find((ele) => ele.value === value)
            return _value ? _value.label : ''
          }
        },
        {
          prop: 'maxLength',
          label: '数据长度',
          minWidth: '120'
        },
        {
          prop: 'mapperToDb',
          label: '是否与DB映射',
          minWidth: '120',
          showLabel(value) {
            const _value = MAPPERTODB.find((ele) => ele.value === value)
            return _value ? _value.label : ''
          }
        },
        {
          prop: 'dbFieldCode',
          label: 'DB字段编码',
          minWidth: '120'
        },
        {
          prop: 'dbFieldDataType',
          label: 'DB字段数据类型',
          minWidth: '120',
          showLabel(value) {
            const _value = DATATYPE.find((ele) => ele.value === value)
            return _value ? _value.label : ''
          }
        },
        {
          prop: 'updatePrimaryField',
          label: '更新主键',
          minWidth: '120',
          showLabel(value) {
            const _value = REQUIRED.find((ele) => ele.value === value)
            return _value ? _value.label : ''
          }
        },
        {
          prop: 'valueMapType',
          label: '映射类型',
          minWidth: '120',
          showLabel(value) {
            const _value = VALUEMAPTYPE.find((ele) => ele.value === value)
            return _value ? _value.label : ''
          }
        },
        {
          prop: 'sqlContent',
          label: '抽取sql',
          minWidth: '120'
        },
        {
          prop: 'codeType',
          label: '字典类型',
          minWidth: '120'
        },
        {
          prop: 'pidDbFieldCode',
          label: '主键',
          minWidth: '120'
        },
        {
          prop: 'pidRelExcelColumnCodes',
          label: 'excel关联字段',
          minWidth: '120'
        },
        {
          prop: 'pidRelDbFieldCodes',
          label: '关联表字段',
          minWidth: '120'
        },
      ],
      fieldList: [],
      uniqueValid: [],
      dialog: {
        visible: false,
        isEdit: false,
        items: [],
        isInit: true
      },
      uniqueValidDailog: {
        visible: false,
        defaultValue: []
      }
    }
  },
  methods: {
    handleRowClick(row) {
      this.$refs.Table && this.$refs.Table.toggleRowSelection(row, !row.flag)
    },
    handleSelectionChange(selection) {
      const ids = selection.map((ele) => ele.id)
      this.fieldList.forEach((row) => {
        row.flag = ids.includes(row.id)
      })
    },
    handleAdd() {
      this.$refs.Form && this.$refs.Form.resetFields()
      const items = getFieldFormItems({ fieldList: this.fieldList, tableName: this.data.tableName })
      this.dialog.items = items
      this.dialog.visible = true
      this.dialog.isEdit = false
    },
    handleEdit() {
      const selection = this.$refs.Table.selection
      if (selection.length !== 1) {
        this.$message({
          message: '请选择要编辑的一条数据',
          type: 'warning'
        })
        return
      }
      this.$refs.Form && this.$refs.Form.resetFields()
      const row = selection[0]
      const fieldFormItems = getFieldFormItems({ fieldList: this.fieldList, tableName: this.data.tableName })
      const items = []
      for (let i = 0; i < fieldFormItems.length; i++) {
        const element = fieldFormItems[i]

        if (['relFieldSelect'].includes(element.prop)) {
          const relField = row.pidRelDbFieldCodes?.split(',') || []
          const relExcelFields = row.pidRelExcelColumnCodes?.split(',') || []
          relField.forEach((ele, i) => {
            element.attrs.defaultValue.push({
              id: i + new Date().getTime(),
              relExcelField: relExcelFields[i] || '',
              relField: ele || ''
            })
          })
        }

        if (row && row.hasOwnProperty([element.prop])) {
          if (['dbFieldCode', 'pidDbFieldCode'].includes(element.prop)) {
            element.defaultValue = row[element.prop] ? [{ fieldCode: row[element.prop], dataType: row.dbFieldDataType}] : null
          } else if (['valueMapType'].includes(element.prop)) {
            element.defaultValue = row[element.prop] || 'D_MAP'
          } else if (['updatePrimaryField'].includes(element.prop)) {
            element.defaultValue = row[element.prop] || false
          } else {
            element.defaultValue = row[element.prop]
          }
        }
        items.push(element)
      }

      this.dialog.items = items
      this.dialog.visible = true
      this.dialog.isEdit = true
    },
    handleDelete() {
      const selection = this.$refs.Table.selection
      if (!selection.length) {
        this.$message({
          type: 'warning',
          message: '请选择需要删除的数据！'
        })
        return
      }
      this.$confirm('是否确认删除字段？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const selectionNames = selection.map((ele) => ele.excelColumnCode)
          this.fieldList = this.fieldList.filter(
            (ele) => !selectionNames.includes(ele.excelColumnCode)
          )
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {})
    },
    handleTableSelectOpen(formData, { items, item }, tableSelectDialog) {
      const { pager, keyword } = tableSelectDialog
      if (['dbFieldCode', 'pidDbFieldCode'].includes(item.prop)) {
        getFieldListByTable(
          this.data.tableName,
          pager.pageNum,
          pager.pageSize,
          keyword
        ).then((res) => {
          tableSelectDialog.tableData = res.data.records
          tableSelectDialog.pager.total = res.data.total
        })
      }
    },
    handleUniqueVerifySetting() {
      this.$refs.UniqueValidDailog && this.$refs.UniqueValidDailog.resetFields()
      this.uniqueValidDailog.defaultValue = this.uniqueValid.map((ele, i) => {
        return {
          ...ele,
          _id: i + new Date().getTime()
        }
      })
      this.uniqueValidDailog.visible = true
    },
    handleSubmitForm(formData) {
      const _formData = JSON.parse(JSON.stringify(formData))
      // DB字段编码
      if (Object.prototype.toString.call(formData.dbFieldCode) === '[object Array]') {
        _formData.dbFieldCode = formData.dbFieldCode[0]?.fieldCode || ''
      }
      // 主键
      if (Object.prototype.toString.call(formData.pidDbFieldCode) === '[object Array]') {
        _formData.pidDbFieldCode = formData.pidDbFieldCode[0]?.fieldCode || ''
      }
      // 父Id取值关联字段
      if (Object.prototype.toString.call(formData.relFieldSelect) === '[object Array]') {
        _formData.pidRelDbFieldCodes = formData.relFieldSelect.map((ele) => ele.relField).join(',')
        _formData.pidRelExcelColumnCodes = formData.relFieldSelect
          .map((ele) => ele.relExcelField)
          .join(',')
        delete _formData.relFieldSelect
      }
      // 是否与DB映射 / 映射类型
      if (formData.mapperToDb === false) {
        _formData.dbFieldCode = null
        _formData.dbFieldDataType = null
        _formData.updatePrimaryField = null
        _formData.valueMapType = null
        _formData.codeType = null
        _formData.sqlContent = null
        _formData.pidDbFieldCode = null
        _formData.pidRelDbFieldCodes = null
        _formData.pidRelExcelColumnCodes = null
      } else if (formData.valueMapType === 'D_MAP') {
        _formData.codeType = null
        _formData.sqlContent = null
        _formData.pidDbFieldCode = null
        _formData.pidRelDbFieldCodes = null
        _formData.pidRelExcelColumnCodes = null
      } else if (formData.valueMapType === 'CODE_VALUE') {
        _formData.sqlContent = null
        _formData.pidDbFieldCode = null
        _formData.pidRelDbFieldCodes = null
        _formData.pidRelExcelColumnCodes = null
      } else if (formData.valueMapType === 'SQL_FETCH') {
        _formData.codeType = null
        _formData.pidDbFieldCode = null
        _formData.pidRelDbFieldCodes = null
        _formData.pidRelExcelColumnCodes = null
      } else if (formData.valueMapType === 'TREE_PID') {
        _formData.codeType = null
        _formData.sqlContent = null
      }

      let fieldRow = this.fieldList.find(
        (ele) => ele.excelColumnCode === _formData.excelColumnCode
      )
      if (fieldRow) {
        fieldRow = Object.assign(fieldRow, _formData)
      } else {
        this.fieldList.push(_formData)
      }
      // 排序
      this.fieldList.sort((a,b) => {
        return Number(a.orderNo) >= Number(b.orderNo) ? 1 : -1
      })

      this.dialog.visible = false
    },
    handleUniqueSubmitForm(formData) {
      this.uniqueValid = formData
      this.uniqueValidDailog.visible = false
    },
    refreshFields(tableName) {
      getAllFieldListByTable(tableName).then((res) => {
        res.data.map((ele) => {
          const obj = ele
          obj.excelColumnCode = ele.fieldCode
          obj.excelColumnName = ele.fieldName || ele.fieldCode
          obj.required = false
          obj.excelColumnDataType = ele.dataType
          obj.mapperToDb = true
          obj.dbFieldCode = ele.fieldCode
          obj.dbFieldDataType = ele.dataType
          obj.updatePrimaryField = false
          obj.valueMapType = 'D_MAP'
          obj.sqlContent = null
          obj.codeType = null
          obj.pidDbFieldCode = null
          obj.pidRelExcelColumnCodes = null
          obj.pidRelDbFieldCodes = null
          return obj
        })
        this.fieldList = res.data
      })
    },
    getFieldData() {
      return this.fieldList
    },
    getUniqueValidData() {
      return this.uniqueValid
    }
  },
  watch: {
    data: {
      handler(newVal, oldVal) {
        if (!newVal || newVal.id === oldVal.id) {
          return
        }
        if (newVal?.tree?.id) {
          const fields = JSON.parse(JSON.stringify(newVal.fields))
          // 初始化updatePrimaryField字段
          this.fieldList = fields.map((ele) => {
            const obj = ele
            obj.required = obj.required === true
            obj.mapperToDb = obj.mapperToDb === true
            obj.updatePrimaryField = obj.updatePrimaryField === true
            return obj
          })
          this.uniqueValid = newVal.uniqueChecks || []
        } else {
          // 新增的节点
        }
      },
      deep: true
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog .el-dialog__body {
  max-height: calc(100vh - 26rem);
}
.field-form-container {
  height: 100%;
  .table-container {
    width: 100%;
    height: calc(100% - 10px - 28px);
    margin-top: 10px;
  }
}
.model-form {
  .el-form-item {
    width: 50%;
    float: left;
  }
  .el-icon-search {
    cursor: pointer;
  }
}
</style>